package com.by.service.impl;


import com.by.bean.UserFinally;
import com.by.bean.UserType;
import com.by.common.ex.BusinessException;
import com.by.common.utils.Assert;
import com.by.bean.Customer;
import com.by.common.bean.PageBean;
import com.by.common.crud.BaseServiceImpl;
import com.by.mapper.CustomerMapper;
import com.by.mapper.UserFinallyMapper;
import com.by.query.CustomerQuery;
import com.by.service.CustomerService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.List;

@Service
public class CustomerServiceImpl extends BaseServiceImpl<Customer, CustomerMapper> implements CustomerService {

    @Autowired
    CustomerMapper customerMapper;
    @Autowired
    UserFinallyMapper userMapper;

    @Override
    public PageBean queryByMap(CustomerQuery query) {
        //分页查询
        PageHelper.startPage(query.getPage(), query.getPageSize());//后面紧跟查询
        List list = customerMapper.queryByMap(query);
        PageInfo info = new PageInfo(list);
        return new PageBean(query.getPage(), query.getPageSize(), info.getTotal(), list);
    }

    @Transactional
    @Override
    public int save(Customer customer) {
        int c=userMapper.queryUserByUserName(customer.getAccount());
        if(c>0)
            throw new BusinessException("该账号已存在！");
        UserFinally user = new UserFinally(customer.getAccount(),customer.getPassword(), UserType.CUSTOMER_USER);
        //save user
        int rs = userMapper.add(user);
        Assert.isZero(rs,"用户保存失败");
        customer.setSaleId(user.getId());
        return super.save(customer);
    }

    @Transactional
    @Override
    public int delete(Serializable id) {
        //删除用户
        int rs=customerMapper.delete(id);
        Assert.isZero(rs,"客户删除失败");
        return super.delete(id);
    }
}
